#include "Viewport.h"
#include "Renderable.h"
#include "util.h"
#include "GraphicFactory.h"

namespace Graphics
{
	Viewport::Viewport(const Rect* pRect)
	{
		// set the default value of render rectangle
		if(pRect == 0)
		{
			GraphicFactory* pGF = GraphicFactory::getInstance();
			
			// avoid Graphic2D add itself
			if(pGF != 0)
			{
				Graphic2D* const g = pGF->GetGraphic2D();
				m_pRenderRect = new Rect(0,0,g->GetWidth(),g->GetHeight());
				g->Add(*this);
			}
			else
			{
				m_pRenderRect = new Rect(0,0,0,0);
			}
		}
		else
		{
			m_pRenderRect = new Rect(pRect->left,pRect->top,pRect->right,pRect->bottom);
		}
	}

	Viewport::~Viewport(void)
	{
		Graphic2D* const g = GraphicFactory::getInstance()->GetGraphic2D();
		if( g != this)
		{
			g->Remove(*this);
		}
		delete m_pRenderRect;
	}
	void Viewport::SetSequence(int sequence)
	{
		Renderable::SetSequence(sequence);
		Graphic2D* const g = GraphicFactory::getInstance()->GetGraphic2D();
		if( g != this)
		{
            g->MarkDirty();
		}
	}
	void Viewport::SetRenderRect(const Rect& rect)
	{
		*m_pRenderRect = rect;
	}
	const Rect& Viewport::GetRenderRect(void)
	{
		return *m_pRenderRect;
	}

	bool Viewport::RenderImpl(void)
	{
		return Graphic::RenderAll();
	}
}